<template>
  <div class="subject-tree-content" :class="{ 'select-open': toggleTree, 'select-close': !toggleTree && isready, 'play-running': isready }">
    <px-input v-model="filterText" class="mb-[10px]" clearable placeholder="请填写名称" @input="onQueryChanged" />
    <px-scrollbar>
      <tree-v2
        ref="treeRef"
        :height="470"
        highlight-current
        :expand-on-click-node="false"
        node-key="code"
        empty-text="数据为空"
        :data="treeData"
        :props="defaultProps"
        :filter-method="filterMethod"
        @node-click="nodeClickHandler"
      >
        <template #default="{ data }">
          <div class="w-[150px]" :class="{ notselect: data.eqpType === 'ERC' || data.isClick == 0 }">
            <ReTextTooltip :content="data.type !== 'EQP' ? data.name : `${data.showName}/${data.name}`" />
          </div>
        </template>
      </tree-v2>
    </px-scrollbar>
    <px-button class="refresh-tree" link icon="Refresh" @click="refreshTree" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, computed } from "vue";
import { PxTree } from "px-ui";

import ReTextTooltip from "@/components/ReTextTooltip";
import TreeV2 from "../../config/components/tree-v2/tree.vue";

interface BreadcrumbItem {
  label: string;
  name: string;
  path: string;
  children?: BreadcrumbItem[];
}

const props = withDefaults(
  defineProps<{
    positionCode?: string;
    treeData: Record<string, any>;
    flattenTreeData: Record<string, any>;
    toggleTree: boolean;
  }>(),
  {
    toggleTree: false
  }
);
const filterText = ref("");
const isready = ref(false);
const treeRef = ref<InstanceType<typeof PxTree>>();
const defaultProps = {
  children: "children",
  value: "code",
  label: "name",
  key: "code"
};

onMounted(() => {});
watch(
  () => [props.toggleTree, props.flattenTreeData],
  val => {
    const [toggle] = val;
    if (toggle) {
      setTreeData();
    }
  }
);
function setTreeData() {
  if (treeRef.value) {
    let curBreadcurmb = props.flattenTreeData[props.positionCode];
    const { path } = curBreadcurmb || {};
    let pathArr = path?.split("@") || [];
    if (pathArr.length > 0) {
      nextTick(() => {
        treeRef.value.setExpandedKeys(pathArr);
        treeRef.value.setCurrentKey(props.positionCode);
        setTimeout(() => {
          //确保树渲染完后进行滚动
          if (props.positionCode) treeRef.value.scrollToNode(props.positionCode, "start");
          isready.value = true;
        }, 0);
      });
    }
  }
}
const routerTree = computed(() => {
  return props.treeData[props.positionCode] ? [props.treeData[props.positionCode]] : [];
});
const emit = defineEmits<{
  (e: "router-click", item: BreadcrumbItem): void;
  (e: "refresh-tree"): void;
}>();

const nodeClickHandler = (data, node) => {
  const { type, code, eqpType } = data;
  if (eqpType === "ERC" || data.isClick == 0) {
    nextTick(() => {
      const selectedNodes = document.querySelectorAll(".is-current");
      selectedNodes.forEach(element => {
        element.classList.remove("is-current");
      });
    });
    return false;
  }
  emit("router-click", { code: data.code, type });
};

const onQueryChanged = (query: string) => {
  // TODO: fix typing when refactor tree-v2
  treeRef.value!.filter(query);
};

const filterMethod = (query: string, node) => {
  const { showName, name, code, type } = node;
  if (type === "EQP") {
    return name!.indexOf(query) !== -1 || showName?.indexOf(query) !== -1;
  }
  return name!.indexOf(query) !== -1 || code?.indexOf(query) !== -1;
};
const refreshTree = () => {
  emit("refresh-tree");
};
</script>

<style scoped lang="scss">
/* 逐渐展开的动画 */
@keyframes slide-down {
  0% {
    width: 0;
    padding: 0;
  }

  100% {
    width: 300px;
    padding: 12px;
  }
}

/* 逐渐收起的动画 */
@keyframes slide-up {
  0% {
    width: 300px;
    padding: 12px;
  }

  100% {
    width: 0;
    padding: 0;
  }
}

.subject-tree-content {
  position: absolute;
  top: 60px;
  left: 16px;
  z-index: 99;
  width: 0;
  height: 550px;
  padding: 0;
  overflow: hidden;
  overflow-x: auto;
  background: #fff;
  backdrop-filter: blur(10px);
  border-radius: 8px;
  box-shadow: 0 1px 4px 0 rgb(0 0 0 / 16%);
  opacity: 0.75;
  animation-play-state: paused;
}

.play-running {
  animation-play-state: running;
}

/* 打开时使用的动画 */
.select-open {
  transform-origin: top center;
  animation: slide-down 0.3s ease-out forwards;
}

/* 关闭时使用的动画 */
.select-close {
  transform-origin: top center;
  animation: slide-up 0.3s ease-in forwards;
}

.notselect {
  cursor: not-allowed;
}

.refresh-tree {
  position: absolute;
  bottom: 0;
  left: 0;

  svg {
    outline: none;
  }
}
</style>
